<template>
    <view class="container" :style="themeColor">
        <view class="main">
            <view class="custom-cell">
                <text class="cell-label">收货人</text>
                <view class="cell-main"
                    ><input class="cell-input" type="text" v-model="data.ContactName" placeholder="请填写收货人"
                /></view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">联系电话</text>
                <view class="cell-main">
                    <input
                        class="cell-input"
                        maxlength="11"
                        type="number"
                        v-model="data.ContactTel"
                        placeholder="请填写联系电话" />
                </view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">地区选择</text>
                <view class="cell-main" @click="areaSelectFn">
                    <text class="cell-value">{{ regionName }}</text>
                    <uni-icons type="arrowright"></uni-icons>
                </view>
            </view>
            <view class="custom-cell">
                <textarea
                    class="cell-textarea"
                    placeholder="请填写详细地址(街道、楼牌号等)"
                    v-model="data.ContactAddress"></textarea>
                <uni-icons class="icon-location" type="location-filled" size="48" @click="getLoaction"></uni-icons>
            </view>
            <view class="pd10">
                <view class="custom-cell posr">
                    <textarea
                        class="cell-textarea"
                        placeholder="提示：黏贴地址信息可快速添加收货地址，例如：张三18000000000福建省泉州市XXXX"
                        v-model="identifyAddress"></textarea>
                    <view @click="identify" class="identify">识别</view>
                </view>
                <view class="placeholder-text">提示：黏贴地址信息可快速添加收货地址，例如：张三18000000000福建省泉州市XXXX</view>
            </view>
        </view>
        <view class="card-cell">
            <text class="cell-label">设为默认地址</text>
            <switch
                class="cell-switch"
                :color="easyGetColor()"
                :checked="data.IsDefault"
                @change="change('checked', $event.detail.value)" />
        </view>
        <view class="action-bar">
            <text class="btn btn-success" @click="save">保存地址</text>
            <text class="btn btn-gray" v-if="isEidt" @click="del">删除地址</text>
        </view>
        <uni-popup ref="pick" type="dialog">
            <uni-popup-dialog
                type="text"
                title="温馨提示"
                content="确定删除该地址?"
                :before-close="true"
                @close="close"
                @confirm="doDel"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="areaSelect" type="bottom" background-color="#fff" :safe-area="false">
            <area-select :address-data="data" @pickArea="pickArea"></area-select>
        </uni-popup>
		<privacy-agreement></privacy-agreement>
    </view>
</template>

<script>
import searchBar from "@/components/common/search-bar.vue"
import areaSelect from "@/uni-sub-base/components/area-select/area-select.vue"

import { userAddressAddOrEdit, userAddressDelete, batchSmartParse } from "@/service/api/member.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
import privacyAgreement from "@/components/privacy-agreement/privacy-agreement.vue"
import permision from "@/utils/permission.js"
import authorizeUtils from "@/utils/authorizeUtils.js"
import utils from "@/utils/utils.js"
import config from "@/config/config.js"
export default {
    components: {
        searchBar,
        areaSelect,
		privacyAgreement
    },
    data() {
        return {
            placeholderText: "搜索已有地址",
            searchKey: "",
            data: {
                AddressName: "",
                ContactName: "",
                ContactTel: "",
                ContactAddress: "",
                IsDefault: false,
                ProvinceId: 0,
                ProvinceName: "",
                CityId: 0,
                CityName: "",
                AreaId: 0,
                AreaName: "",
                StreetId: 0,
                StreetName: "",
                Longitude: 0,
                Latitude: 0,
                ZipCode: null,
            },
            isEidt: false,
            regionName: "请选择省、市、区",
            identifyAddress: "",
        }
    },
    onLoad(e) {
        if (e.data) {
            this.data = JSON.parse(decodeURIComponent(e.data))

            this.isEidt = true
            this.getRegionName()
        } else {
            uni.setNavigationBarTitle({
                title: "新增地址",
            })
        }
    },
    mounted() {},
    methods: {
        //设置默认地址
        change(name, value) {
            this.data.IsDefault = value
        },
        //保存
        save() {
            //必填值校验
            if (this.data.ContactName.trim() == "") {
                this.easyToast("请填写收货人")
                return
            }
            if (this.data.ContactTel.trim() == "") {
                this.easyToast("请填写联系电话")
                return
            }
            if (this.data.ContactTel.length < 11) {
                this.easyToast("请正确填写联系电话")
                return
            }
            if (this.data.ContactAddress.trim() == "") {
                this.easyToast("请填写详细地址")
                return
            }
            // if (!this.data.Longitude || !this.data.Latitude) {
            // 	this.easyToast("请先定位地址")
            // 	return
            // }
            userAddressAddOrEdit(this.data).then((res) => {
                if (res.State == 1) {
                    this.easyToast("提交成功")
                    setTimeout(() => {
                        this.easyGoBack()
                    }, 500)
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //删除
        del() {
            this.$refs.pick.open()
        },
        //取消
        close() {
            this.$refs.pick.close()
        },
        //确认删除
        doDel() {
            this.close()
            let param = {
                ids: this.data.ID,
            }
            userAddressDelete(param).then((res) => {
                if (res.State == 1) {
                    this.easyToast("删除成功")
                    setTimeout(() => {
                        this.easyGoBack()
                    }, 500)
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //选择地区
        areaSelectFn() {
            this.$refs.areaSelect.open()
        },
        //选择地区回调
        pickArea(data) {
            this.$refs.areaSelect.close()
            this.data = Object.assign(this.data, data)
            this.getRegionName()
        },
        getRegionName() {
            let line = "-"
            this.regionName = `${this.data.ProvinceName || ""}-${this.data.CityName || ""}${
                this.data.AreaName ? line + this.data.AreaName : ""
            }${this.data.StreetName ? line + this.data.StreetName : ""}`
            // this.data.ProvinceName?this.data.ProvinceName:'' +
            // this.data.CityName?"-"+this.data.CityName:''+
            // this.data.AreaName?"-"+this.data.AreaName:''+
            // this.data.StreetName?"-"+this.data.StreetName:''
        },
		//#ifdef APP
		getLoaction() {
		   return new Promise(async (resolve) => {
			   let authFlag = await authorizeUtils.showAuthTipModal("android.permission.ACCESS_FINE_LOCATION")
			   if (!authFlag) return resolve(null)
						let that = this
						uni.chooseLocation({
							success: function (res) {
								console.log(res)
								console.log("位置名称：" + res.name)
								console.log("详细地址：" + res.address)
								console.log("纬度：" + res.latitude)
								console.log("经度：" + res.longitude)
								that.getAppP(res)
								that.data.ContactAddress = res.name
								that.data.Longitude = res.longitude
								that.data.Latitude = res.latitude
							},
							fail: (fail) => {
								that.hideLoading()
								authorizeUtils.showManualAuth("android.permission.ACCESS_FINE_LOCATION")
								return resolve(null)
							}
						})
		   })
	    },
		//#endif
		// #ifndef APP
        getLoaction() {
            //#ifdef MP-WEIXIN
            this.getCenterLocation()
            //#endif
            //#ifdef APP
				uni.navigateTo({
					url: "/pages_me/packet/map/map-poi",
					events: {
						getSelectData: (data) => {
							this.getAppP(data)
							this.data.Longitude = data.location.longitude
							this.data.Latitude = data.location.latitude
							this.data.ContactAddress = data.name + data.address.replace(/\\/g, "")
						},
					},
				})
            //#endif
            //#ifdef H5
            getLocation(
                (res) => {
                    if (res) {
                        this.data.ContactAddress = res.address.street + res.address.streetNum

                        this.getP(res.address)
                    }
                },
                (err) => {
                    console.log(err)
                },
            )
            //#endif
        },
		//#endif
        getCenterLocation() {
            var that = this
            wx.authorize({
                scope: "scope.userLocation",
                complete: function (res) {
                    wx.chooseLocation({
                        success(str) {
                            //发送请求通过经纬度反查地址信息
							var getAddressUrl ='https://restapi.amap.com/v3/geocode/regeo?output=JSON&location='+str.longitude+','+str.latitude +
                                "&key=" +config.aMapKey.wx
                            wx.request({
								header: {
									'Content-Type': 'application/text',
								},
                                url:getAddressUrl,
                                success: function (result) {
                                    var province = result.data.regeocode.addressComponent.province
                                    var city = result.data.regeocode.addressComponent.city
                                    var district = result.data.regeocode.addressComponent.district
                                    var address = result.data.regeocode.addressComponent.township+result.data.regeocode.addressComponent.streetNumber.street+result.data.regeocode.addressComponent.streetNumber.number

                                    // that.data.ContactAddress =province+city+district+address
                                    that.data.Longitude = str.longitude
                                    that.data.Latitude = str.latitude
                                    that.getmapP(
                                       result.data.regeocode.addressComponent,
									   address
                                    )
                                },
								fail(err) {
									console.log(err,"获取位置失败信息")
								}
                            })
                        },
						fail: function (err) {
							console.log(err)
						}
                    })
                },
				fail(err) {
					colsole.log(err)
				}
            })
        },
        getP(res) {
            let item = {
                ContactAddress: res.street + res.streetNum,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreeName: res.street,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getAppP(res) {
            let item = {
                ContactAddress: res.address,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getmapP(res,address) {
            let item = {
                ContactAddress: address,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreetName: res.township,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        //智能识别
        batchSmartParse(param) {
            batchSmartParse(param).then((res) => {
                if (res.Data && res.Data.list && res.Data.list.length > 0) {
                    let result = res.Data.list[0]
                    this.data.ProvinceId = result.ProvinceId
                    this.data.ProvinceName = result.ProvinceName
                    this.data.CityId = result.CityId
                    this.data.CityName = result.CityName
                    this.data.AreaId = result.AreaId
                    this.data.AreaName = result.AreaName
                    this.data.StreetId = result.StreetId
                    this.data.StreetName = result.StreetName
                    this.data.ContactAddress = result.ContactAddress
                    this.data.ContactName = result.ContactName
                    this.data.ContactTel = result.ContactTel
                    this.getRegionName()
                }
            })
        },
        identify(){
            console.log('开始识别')
            let addressStr = this.identifyAddress
            addressStr = addressStr.replace(/；/g, ';') // 去掉空格
            if (/1\d{9}.*\n.*1\d{9}/.test(addressStr)) {
               addressStr = addressStr.replace(/\n/g, ';')
            }
            addressStr = addressStr.replace(/\s/g, '')
            if (addressStr.charAt(addressStr.length - 1) === ';') {
               addressStr = addressStr.substring(0, addressStr.length - 1)
            }
            const targetAds = addressStr.split(';')[0]
            var backinfo = utils.AutoDistinguishAddress(targetAds)
            let item = {
                ContactName: backinfo.name.replace(/[,|，|；|;|\s]/g, ""),               
                ContactAddress: backinfo.address.replace(/[,|，|；|;|\s]/g, ""),
                ContactTel: backinfo.phone.replace(/[,|，|；|;|\s]/g, ""),
            }
            let list = []
            list.push(item)
            let param = {
               list: list,
            }
            this.batchSmartParse(param)
        },
    },
}
</script>

<style lang="scss">
.container {
    padding: $app-page-padding;
}

.main {
    margin-bottom: 40rpx;
    background: $color-white;
    border-radius: $border-radius-10;
}

.action-bar {
    display: flex;
    flex-direction: column;

    .btn {
        margin-left: 0;
        margin-bottom: 20rpx;
        height: 80rpx;
        font-size: 32rpx;
    }
}

.custom-cell {
    display: flex;
    flex-direction: row;
    align-items: center;
    min-height: 66rpx;
    padding: $app-page-padding;
    border-bottom: solid 1rpx $uni-bg-color-grey;

    &:last-child {
        border-bottom: 0;
    }

    .cell-label {
        display: flex;
        flex: 1;
    }

    .cell-main {
        display: flex;
        flex: 3;
        overflow: hidden;

        .cell-value {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: $app-color-text-desc;
            font-size: $font-size-28;
        }

        .cell-input {
            color: $app-color-text-desc;
            font-size: $font-size-28;
        }
    }

    .cell-textarea {
        height: 160rpx;
        color: $app-color-text-desc;
        font-size: $font-size-28;
    }

    .icon-location {
        padding: $app-page-padding;
        margin-right: -$app-page-padding;
    }
}

.card-cell {
    margin-bottom: 40rpx;
}

.cell-switch {
    transform: scale(0.8);
}
.placeholder-text {
    font-size: 20rpx;
    line-height: 1.5;
}
.identify{
    position: absolute;
    bottom: 24rpx;
    right: 24rpx;
    background: #333;
    color: #fff;
    font-size: 24rpx;
    padding: 0 20rpx;
    line-height: 40rpx;
    z-index: 10;
}
.pd10{
    padding: 20rpx;
}
.posr{
    position: relative;
    background: #f4f4f4;
}
</style>
